import React, { useState } from 'react';
import axios from 'axios';
import './MatchListTab.css';

const MatchListTab = () => {
    const [matches, setMatches] = useState([]);
    const [loading, setLoading] = useState(false);
    const [exporting, setExporting] = useState(false);

    // 获取比赛数据
    const fetchNewMatches = async () => {
        try {
            setLoading(true);
            const url = 'https://webapi.sporttery.cn/gateway/uniform/fb/getMatchDataPageListV1.qry?method=concern';

            // 使用后端代理避免跨域问题
            const response = await axios.get('/api/lottery/newMatches', {
                params: { url }
            });

            // 解析数据
            const allMatches = [];
            if (response.data.success && response.data.value && response.data.value.matchInfoList) {
                response.data.value.matchInfoList.forEach(info => {
                    if (info.subMatchList && info.subMatchList.length > 0) {
                        info.subMatchList.forEach(match => {
                            allMatches.push(match);
                        });
                    }
                });
            }

            setMatches(allMatches);
        } catch (error) {
            console.error('获取比赛数据失败:', error);
            alert('获取比赛数据失败，请重试');
        } finally {
            setLoading(false);
        }
    };

    // 导出比赛数据
    const exportMatches = () => {
        if (matches.length === 0) {
            alert('没有可导出的比赛数据，请先获取数据');
            return;
        }

        setExporting(true);

        try {
            // 获取当前日期 20250918格式
            const today = new Date();
            const dateStr = today.getFullYear() +
                String(today.getMonth() + 1).padStart(2, '0') +
                String(today.getDate()).padStart(2, '0');

            // 构建导出内容
            let content = `比赛数据_${dateStr}\n\n`;
            matches.forEach(match => {
                // 从matchNumStr中提取001,002等编号
                const matchNum = match.matchNumStr ? match.matchNumStr.replace(/[^\d]/g, '') : '';
                if (matchNum) {
                    content += `${matchNum}   ${match.homeTeamAbbName}vs${match.awayTeamAbbName}\n`;
                }
            });

            // 创建下载链接
            const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `比赛列表_${dateStr}.txt`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        } catch (error) {
            console.error('导出失败:', error);
            alert('导出失败，请重试');
        } finally {
            setExporting(false);
        }
    };

    return (
        <div className="match-list-tab">
            <div className="match-list-controls">
                <button
                    className="fetch-btn"
                    onClick={fetchNewMatches}
                    disabled={loading}
                >
                    {loading ? '获取中...' : '获取比赛数据'}
                </button>
                <button
                    className="export-btn"
                    onClick={exportMatches}
                    disabled={exporting || matches.length === 0}
                >
                    {exporting ? '导出中...' : '导出比赛列表'}
                </button>
            </div>

            {loading ? (
                <div className="loading">加载中...</div>
            ) : (
                <div className="matches-list">
                    {matches.length > 0 ? (
                        <table className="matches-table">
                            <thead>
                            <tr>
                                <th>编号</th>
                                <th>联赛</th>
                                <th>比赛</th>
                                <th>时间</th>
                                <th>状态</th>
                            </tr>
                            </thead>
                            <tbody>
                            {matches.map((match, index) => (
                                <tr key={match.matchId || index}>
                                    <td>{match.matchNumStr || ''}</td>
                                    <td>{match.leagueAbbName || ''}</td>
                                    <td>
                                        <span className="home-team">{match.homeTeamAbbName}</span>
                                        <span className="vs">vs</span>
                                        <span className="away-team">{match.awayTeamAbbName}</span>
                                    </td>
                                    <td>{`${match.matchDate} ${match.matchTime}`}</td>
                                    <td>{match.matchStatusName || ''}</td>
                                </tr>
                            ))}
                            </tbody>
                        </table>
                    ) : (
                        <div className="no-data">暂无数据，请点击"获取比赛数据"按钮</div>
                    )}
                </div>
            )}
        </div>
    );
};

export default MatchListTab;